from rest_framework.viewsets import ModelViewSet

from user.user_serializers import UserModelSerializer

from django.contrib.auth.hashers import make_password, check_password
from rest_framework.response import Response
from rest_framework.views import APIView
from serializers.user_serializer import UserSeialiser

from user.models import User


class UserView(ModelViewSet):

    queryset = User.objects.all()
    serializer_class = UserModelSerializer

# 用户中心
class UserInfoView(APIView):
    def get(self, request):
        user = request.user
        serializer = UserSeialiser(instance=user)
        return Response(serializer.data)

    def put(self, request):
        user = request.user
        data = request.data
        serializer = UserSeialiser(instance=user,data=data, partial=True)
        result = serializer.is_valid(raise_exception=True)
        if result:
            serializer.save()
            return Response(serializer.data)


# 修改密码
class UpdatePasswordView(APIView):

    def put(self, request):

        data = request.data
        try:
            user = request.user
            user.password = make_password(data['password'])
            user.save()
        except Exception as e:
            return Response({'success': False, "message": '修改密码失败'})
        return Response({'success': True, "message": 'ok'})


# 关注
class LikeView(APIView):

    def post(self, request, id):

        user2 = request.user
        user1 = User.objects.get(id=id)
        try:
            user1.fans.add(user2)
            user1.save()
            user2.save()
        except Exception as e:
            return Response({'success': False, 'message': '关注失败'})
        return Response({'success': True, 'message': '关注成功'})

    def delete(self, request, id):
        user2 = request.user
        user1 = User.objects.get(id=id)
        try:
            user1.fans.remove(user2)
        except Exception as e:
            return Response({'success': False, 'message': '关注失败'})
        return Response({'success': True, 'message': '取消关注成功'})

